import axios from 'axios';
import type { AxiosInstance } from 'axios';
import { showMessage } from '../utils/message';

const BASE_URL = 'http://localhost:8005/problem/';

export interface Problem {
  id: number;
  title: string;
  difficulty: string;
  source: string;
  pass_rate: number;
  total_submissions: number;
  accepted_submissions: number;
  tag: {
    id: number;
    name: string;
  };
  type: {
    id: number;
    name: string;
  };
  create_time: string;
  update_time: string;
}

export interface ProblemListParams {
  page?: number;
  page_size?: number;
  search?: string;
  difficulty?: string;
  ordering?: string;
}

export interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
}

const api: AxiosInstance = axios.create({
  baseURL: BASE_URL,
  timeout: 5000,
});

// Response interceptor
api.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code !== 200) {
      showMessage(res.msg);
      return Promise.reject(res);
    }
    return res;
  },
  (error) => {
    showMessage({
      code: error.response?.status || 500,
      msg: error.response?.data?.msg || '请求失败',
    });
    return Promise.reject(error);
  }
);

const problemApi = {
  // 获取题目列表
  async getList(params: ProblemListParams = {}): Promise<Problem[]> {
    const response = await api.get('', { params });
    return response.data;
  },

  async getCount(params: ProblemListParams = {}): Promise<number> {
    const response = await api.get('/count', { params });
    return response.data;
  },

  // 获取题目详情
  async getDetail(id: number): Promise<Problem> {
    const response = await api.get(`/${id}`);
    return response.data;
  },

  // 获取题目的测试用例
  async getTestCases(id: number): Promise<ApiResponse<any>> {
    const response = await api.get(`/problems/test_cases/${id}`);
    return response.data;
  },

  // 获取题目类型列表
  async getTypes(): Promise<ApiResponse<any>> {
    const response = await api.get('/types');
    return response;
  },

  // 获取题目标签列表
  async getTags(): Promise<ApiResponse<any>> {
    const response = await api.get('/tags');
    return response;
  },

  // 创建题目
  async createProblem(data: any): Promise<ApiResponse<any>> {
    const response = await api.post('', data);
    return response;
  },

  // 更新题目
  async updateProblem(id: number, data: any): Promise<ApiResponse<any>> {
    const response = await api.put(`/${id}`, data);
    return response;
  },

  // 删除题目
  async deleteProblem(id: number): Promise<ApiResponse<any>> {
    const response = await api.delete(`/${id}`);
    return response;
  }
};

export default problemApi;
